//
//  MKUITabBarContentContainerListView.m
//  MKUI
//
//  Created by 苏尚进 on 2023/6/26.
//  Copyright © 2023 moon. All rights reserved.
//

#import "MKUITabBarContentContainerListView.h"
#import "NSObject+MKUI.h"
#import "NSArray+MKUI.h"
#import "UIScrollView+MKUI.h"
#import "MKUITabBarController.h"

@interface __MKUITabBarContentContainerListViewCellView : UIView<MKUIListCellViewProtocol>
@property(nonatomic,strong,nullable) id<MKUITabBarContentProtocol> tabBarContent;
@property(nonatomic,strong,nullable) UIView *tabBarContentView;
@end
@implementation __MKUITabBarContentContainerListViewCellView
- (void)setTabBarContentView:(UIView *)tabBarContentView{
    if(_tabBarContentView==tabBarContentView)return;
    if(_tabBarContentView) [_tabBarContentView removeFromSuperview];
    _tabBarContentView = tabBarContentView;
    [_tabBarContentView removeFromSuperview];
    if(_tabBarContentView) [self addSubview:_tabBarContentView];
}
- (void)layoutSubviews{
    [super layoutSubviews];
    self.tabBarContentView.frame = self.bounds;
}
- (void)listView:(MKUIListView *)listView willDisplayAtIndexPath:(NSIndexPath *)indexPath{
    if(self.tabBarContentView==nil){//延迟加载
        UIView *view = self.tabBarContent.tabBarContentView;
        self.tabBarContentView = view;
    }
    if([self.tabBarContent respondsToSelector:@selector(tabBarContentViewWillAppear:)]){
        [self.tabBarContent tabBarContentViewWillAppear:NO];
    }
    if([self.tabBarContent respondsToSelector:@selector(tabBarContentViewDidAppear:)]){
        [self.tabBarContent tabBarContentViewDidAppear:NO];
    }
}
- (void)listView:(MKUIListView *)listView didEndDisplayingAtIndexPath:(NSIndexPath *)indexPath{
    if([self.tabBarContent respondsToSelector:@selector(tabBarContentViewWillDisapper:)]){
        [self.tabBarContent tabBarContentViewWillDisapper:NO];
    }
    if([self.tabBarContent respondsToSelector:@selector(tabBarContentViewDidDisapper:)]){
        [self.tabBarContent tabBarContentViewDidDisapper:NO];
    }
}
#pragma mark - protocol:MKUIListCellViewProtocol
@end

@interface MKUITabBarContentContainerListView()<MKUIListViewDelegate>{
    CGPoint _preOffset;
    CGVector _scrollVector;
}
@property(nonatomic,strong) MKUIListView *listView;
@property(nonatomic,strong) NSArray<__MKUITabBarContentContainerListViewCellView *> *contentCells;
@property(nonatomic,strong) NSDictionary<NSString *,__MKUITabBarContentContainerListViewCellView *> *contentCellMap;
@end

@implementation MKUITabBarContentContainerListView
- (id)initWithFrame:(CGRect)frame{
    if(self=[super initWithFrame:frame]){
        //
        self.listView = [[MKUIListView alloc] initWithFrame:frame style:(MKUIListViewStylePlain)];
        self.listView.cellInteritemSpacing = 40;
        self.listView.scrollDirection = MKUIListViewScrollDirectionHorizontal;
        self.listView.backgroundColor = UIColor.clearColor;
        self.listView.delegate = self;
        self.listView.decelerationRate = UIScrollViewDecelerationRateFast;
        self.listView.showsVerticalScrollIndicator = NO;
        self.listView.showsHorizontalScrollIndicator = NO;
        [self addSubview:self.listView];
    }
    return self;
}
- (void)layoutSubviews{
    [super layoutSubviews];
    CGRect bounds = self.bounds;
    BOOL sizeChange = !CGSizeEqualToSize(bounds.size, self.listView.frame.size);
    self.listView.frame = bounds;
    if(sizeChange){
        [self.listView reloadDataWithAnimated:NO completion:^(BOOL finished) {
            [self.listView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:self.selectedIndex inSection:0] atScrollPosition:(MKUIListViewScrollPositionMiddle) animated:NO completion:nil];
        }];
    }
}
- (void)setContents:(NSArray<id<MKUITabBarContentProtocol>> *)contents{
    if([self.contents isEqualToArray:contents])return;
    [super setContents:contents];
    NSMutableArray<__MKUITabBarContentContainerListViewCellView *> *contentCells = [[NSMutableArray alloc] initWithCapacity:contents.count];
    NSMutableDictionary<NSString *,__MKUITabBarContentContainerListViewCellView *> *contentCellMap = [[NSMutableDictionary alloc] initWithCapacity:contents.count];
    for(NSObject<MKUITabBarContentProtocol> * c in contents){
        NSString *key = c.mk_objectAddress;
        __MKUITabBarContentContainerListViewCellView *v = self.contentCellMap[key];
        if(!v){
            v = [[__MKUITabBarContentContainerListViewCellView alloc] init];
            v.tabBarContent = c;
        }
        [contentCells addObject:v];
        contentCellMap[key] = v;
    }
    self.contentCells = contentCells;
    self.contentCellMap = contentCellMap;
}
- (void)reloadDataWithAnimated:(BOOL)animated{
    [self.listView deleteAllSections];
    [self.listView addSection];
    for(__MKUITabBarContentContainerListViewCellView *v in self.contentCells){
        [self.listView addItem:v];
    }
    [self.listView reloadDataWithAnimated:animated completion:^(BOOL finished) {
        [self.listView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:self.selectedIndex inSection:0] atScrollPosition:(MKUIListViewScrollPositionMiddle) animated:animated completion:nil];
    }];
}
- (void)setSelectedIndex:(NSInteger)index animated:(BOOL)animated{
    [self setSelectedIndex:index];
    [self.listView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:self.selectedIndex inSection:0] atScrollPosition:(MKUIListViewScrollPositionMiddle) animated:animated completion:nil];
}
#pragma mark - delegate:MKUIListViewDelegate
- (CGSize)listView:(MKUIListView *)listView sizeThatFits:(CGSize)size forCell:(nonnull UIView *)cell forIndexPath:(nonnull NSIndexPath *)indexPath{
    return self.bounds.size;
}

#pragma mark - delegate:UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [self __scrollviewDidEndScrolling:scrollView];
}
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    [self __scrollviewDidEndScrolling:scrollView];
}
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    NSInteger selectedIndex = self.selectedIndex;
    NSArray<NSIndexPath *> *indexPaths = [self.listView indexPathsForVisibleItems];
    NSInteger nextIndex = selectedIndex;
    if(velocity.x>0){//右划动
        nextIndex = indexPaths.lastObject.item;
    }else if(velocity.x<0){//左划动
        nextIndex = indexPaths.firstObject.item;
    }else{
        CGPoint centerPoint = self.listView.mk_centerPointOfContent;
        CGFloat minDis = CGFLOAT_MAX;
        for(NSIndexPath *p in indexPaths){
            CGRect f1 = [self.listView cellForItemAtIndexPath:p].mk_attributeContainerInListView.frame;
            CGFloat dis = ABS(CGRectGetMidX(f1)-centerPoint.x);
            if(dis<minDis){
                nextIndex = p.item;
                minDis = dis;
            }
        }
    }
    UIView *nextCell = [self.listView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:nextIndex inSection:0]];
    *targetContentOffset = nextCell.mk_attributeContainerInListView.frame.origin;
}
- (void)__scrollviewDidEndScrolling:(UIScrollView *)scrollView{
    NSInteger selectedIndex = self.selectedIndex;
    CGVector v = _scrollVector;
    NSArray<NSIndexPath *> *indexPaths = [self.listView indexPathsForVisibleItems];
    NSInteger nextIndex;
    if(v.dx>0){//右划动
        nextIndex = indexPaths.lastObject.item;
    }else{//左划动
        nextIndex = indexPaths.firstObject.item;
    }
    [self.listView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:nextIndex inSection:0] atScrollPosition:(MKUIListViewScrollPositionMiddle) animated:YES completion:nil];
    if(nextIndex!=selectedIndex){
        self.selectedIndex = nextIndex;
        [self.tabBarController contentContainerDidSelectIndex:nextIndex animated:YES];
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGPoint offset = self.listView.contentOffset;
    NSInteger selectedIndex = self.selectedIndex;
    CGRect f1 = [self.listView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:selectedIndex inSection:0]].mk_attributeContainerInListView.frame;
    
    NSInteger nextIndex;
    NSArray<NSIndexPath *> *indexPaths = [self.listView indexPathsForVisibleItems];
    if(offset.x>=f1.origin.x){
        nextIndex = indexPaths.lastObject.item;
    }else{
        nextIndex = indexPaths.firstObject.item;
    }
    if(nextIndex==selectedIndex){
        if(offset.x>f1.origin.x){
            nextIndex = selectedIndex+1;
        }else if(offset.x<f1.origin.x){
            nextIndex = selectedIndex-1;
        }
    }
    nextIndex = MAX(0,nextIndex);
    nextIndex = MIN(self.contents.count-1,nextIndex);
    if(nextIndex!=selectedIndex){
        CGRect f2 = [self.listView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:nextIndex inSection:0]].mk_attributeContainerInListView.frame;
        if(f2.origin.x!=f1.origin.x){
            CGFloat progress = (offset.x-f1.origin.x)/(f2.origin.x-f1.origin.x);
            [self.tabBarController contentContainerDidScrollFrom:selectedIndex to:nextIndex withProgress:progress];
        }
    }
    _scrollVector = CGVectorMake(offset.x-_preOffset.x, offset.y-_preOffset.y);
    _preOffset = offset;
}
@end

@implementation MKUITabBarController (MKUITabBarContentContainerListView)
- (MKUITabBarContentContainerListView *)listViewContentContainer{
    if([self.contentContainer isKindOfClass:[MKUITabBarContentContainerListView class]]){
        return self.contentContainer;
    }
    return nil;
}
@end
